﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Core;

namespace Yuanlin.Business
{
    public class NewsComments : YuanlinUserControl,
        IReplyConverter<NewsReply, GetOperation>,
        IReplyConverter<CommentReply, GetListOperation>
    {
        protected Literal titleLtl;
        protected Repeater list;
        protected Pager pager;
        protected CurrentPage currentPage;
        private News news;
        private EntityList comments;
        public int newsId = UrlManager.Instance.GetParameterValue<int>(YuanlinParameterName.NewsId);
        public string greenNum = UrlManager.Instance.GetParameterValue<string>(YuanlinParameterName.GreenNum);

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetNewsRequest(this));

            CommentListRequest request = new CommentListRequest();
            request.NewsId = newsId;
            request.NewsEntityType = (int)CategoryType.News;
            request.State = 0;
            request.PageIndex = pager.PageIndex;
            request.PageSize = pager.PageSize;
            requestBinders.Add(RequestHelper.BuildGetCommentListRequest(this, request));
        }

        private void BindData()
        {
            if (news != null)
            {
                titleLtl.Text = news.Title.Value;
            }

            list.DataSource = comments;
            list.DataBind();

            if (pager != null && currentPage != null)
            {
                pager.TotalPages = pager.CalculateTotalPages(comments.TotalCount);
                currentPage.TotalRecords = (comments.TotalCount);
                currentPage.TotalPages = pager.TotalPages;
                currentPage.PageIndex = pager.PageIndex;
            }
        }

        #region IReplyConverter<NewsReply,GetOperation> Members

        public void ConvertReply(NewsReply reply, GetOperation operation)
        {
            if (reply != null)
            {
                news = reply.Entity as News;
            }
        }

        #endregion

        #region IReplyConverter<CommentReply,GetListOperation> Members

        public void ConvertReply(CommentReply reply, GetListOperation operation)
        {
            if (reply != null)
            {
                comments = reply.EntityList;

                if (!Page.IsPostBack)
                {
                    BindData();
                }
            }
        }

        #endregion
    }
}
